<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
            :rules="formInfo.rules"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <div class="layui-card-body fullBox table-height layui-col-md6">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="leftFilterInfo.query"
              :filter-list="leftFilterInfo.list"
            >
              <template v-slot:filter-removeEvaluateClass>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeEvaluateClass()"
                  >删除评价分类</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form
                ref="leftTableFormRef"
                :model="leftTableInfo"
                style="width: 100%"
              >
                <page-table
                  ref="leftTableRef"
                  :refresh="leftTableInfo.refresh"
                  :init-curpage="leftTableInfo.initCurpage"
                  v-model:data="leftTableInfo.data"
                  :api="leftTableInfo.api"
                  :pager="false"
                  :query="leftFilterInfo.query"
                  :field-list="leftTableInfo.fieldList"
                  :handle="leftTableInfo.handle"
                  :highlightRow="true"
                  :tab-index="true"
                  :isRowClickSelect="true"
                  row-key="uuid"
                  :tableHeight="350"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-classifyName="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.classifyName`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                required: scope.$index >= 0,
                                message: '请输入评价分类名称',
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                      @click.stop.native=""
                    >
                      <el-input
                        v-model="scope.row.classifyName"
                        placeholder="请输入评价分类名称"
                        :maxlength="50"
                      ></el-input>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
          <div
            class="layui-card-body fullBox table-height layui-col-md6"
            style="padding-left: 20px"
          >
            <!-- 条件栏 -->
            <page-filter
              v-model:query="rightFilterInfo.query"
              :filter-list="rightFilterInfo.list"
            >
              <template v-slot:filter-addEvaluateItems>
                <el-button
                  :disabled="!canAddEvaluateItems"
                  @click="addEvaluateItems()"
                  >添加评分项目</el-button
                >
              </template>
              <template v-slot:filter-removeEvaluateItems>
                <el-button
                  :disabled="!rightTableInfo.selections.length"
                  @click="removeEvaluateItems()"
                  >删除评分项目</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form
                ref="rightTableFormRef"
                :model="rightTableInfo"
                style="width: 100%"
              >
                <page-table
                  ref="rightTableRef"
                  :refresh="rightTableInfo.refresh"
                  :init-curpage="rightTableInfo.initCurpage"
                  v-model:data="rightTableInfo.data"
                  :api="rightTableInfo.api"
                  :pager="false"
                  :query="rightFilterInfo.query"
                  :field-list="rightTableInfo.fieldList"
                  :handle="rightTableInfo.handle"
                  :tab-index="true"
                  :isRowClickSelect="true"
                  :tableHeight="350"
                  :isDynamic="true"
                  @handleEvent="handleEventRight"
                >
                  <template v-slot:col-itemScore="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.itemScore`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                required: scope.$index >= 0,
                                message: '请输入分值',
                                trigger: 'blur',
                              },
                              {
                                validator: $validate.positiveScore,
                                trigger: ['blur', 'change'],
                              },
                            ]
                          : []
                      "
                      @click.stop.native=""
                    >
                      <el-input-number
                        v-model.lazy="scope.row.itemScore"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="9999"
                        @change="onchange($event, scope.row, scope.$index)"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <select-evaluate-items
      v-if="selectEvaluateItemsInfo.visible"
      v-model:show-dialog="selectEvaluateItemsInfo.visible"
      :query="selectEvaluateItemsInfo.query"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectEvaluateItemsCallBack"
    />
  </div>
</template>

<script setup name="evaluationSystemModify">
import PageFilter from '@/components/PageFilter/index'
import PageTable from '@/components/PageTable/index'
import {
  getEvaluateTemplateById,
  createEvaluateTemplate,
  updateEvaluateTemplate,
} from '@/api/evaluate.js'
import PageForm from '@/components/PageForm/index'

import SelectEvaluateItems from '@/components/SelectEvaluateItems/index'
import Sortable from 'sortablejs'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'title', 'id'])

// 过滤相关配置
const leftFilterInfo = reactive({
  query: {},
  list: [
    {
      type: 'button',
      label: '新增评价分类',
      event: addEvaluateClass,
    },
    { type: 'slot', value: 'removeEvaluateClass' },
  ],
})
const rightFilterInfo = reactive({
  query: {},
  list: [
    { type: 'slot', value: 'addEvaluateItems' },
    { type: 'slot', value: 'removeEvaluateItems' },
  ],
})
// 表格相关
const leftTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [
    { label: '评价分类名称', value: 'classifyName', type: 'slot' },
    { label: '分值', value: 'classifyScore' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeEvaluateClass,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
// 表格相关
const rightTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [
    { label: '评价项目名称', value: 'itemName' },
    { label: '分值', value: 'itemScore', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeEvaluateItems,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
// 表单相关
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '评价体系名称',
      value: 'templateName',
      type: 'input',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      max: 200,
    },
  ],
  rules: {
    templateName: [
      { required: true, message: '请输入评价体系名称', trigger: 'blur' },
    ],
  },
  labelWidth: '160px',
})
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectEvaluateItemsInfo = reactive({
  visible: false,
  query: {
    idNotIn: '',
  },
})
const currentRow = ref(null)
const formRefs = ref([])

watch(
  () => rightTableInfo.data,
  (val) => {
    let itemScore = 0
    if (val.length) {
      val.forEach((item) => {
        itemScore = proxy.$fn.accAdd(itemScore, item.itemScore || 0)
      })
    }
    leftTableInfo.data.forEach((item) => {
      if (currentRow.value && item.uuid === currentRow.value.uuid) {
        item['classifyScore'] = itemScore
      }
    })
  },
  {
    immediate: true,
    deep: true,
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveProduct = computed(() => {
  return leftTableInfo.selections.length
})
const canAddEvaluateItems = computed(() => {
  return leftTableInfo.data.length
})

onMounted(() => {
  proxy.$nextTick(() => {
    dragRow()
  })
  if (props.id) {
    getMain()
  }
  formRefs.value = [
    formInfo.ref,
    proxy.$refs['leftTableFormRef'],
    proxy.$refs['rightTableFormRef'],
  ]
})

// 行拖拽
function dragRow() {
  //左
  const tbody = proxy.$refs.leftTableRef.$el.querySelectorAll(
    '.el-table__body-wrapper > table > tbody'
  )[0]
  Sortable.create(tbody, {
    draggable: '.el-table__row',
    animation: 150,
    onEnd({ newIndex, oldIndex }) {
      const currRow = leftTableInfo.data.splice(oldIndex, 1)[0]
      leftTableInfo.data.splice(newIndex, 0, currRow)
    },
  })

  //右
  const _tbody = proxy.$refs.rightTableRef.$el.querySelectorAll(
    '.el-table__body-wrapper > table > tbody'
  )[0]
  Sortable.create(_tbody, {
    draggable: '.el-table__row',
    animation: 150,
    onEnd({ newIndex, oldIndex }) {
      const _currRow = rightTableInfo.data.splice(oldIndex, 1)[0]
      rightTableInfo.data.splice(newIndex, 0, _currRow)
    },
  })
}
function onchange(e, row, $index) {
  rightTableInfo.data.forEach((item) => {
    if (item.id === row.id) {
      proxy.$refs.rightTableFormRef.clearValidate(`data.${$index}.itemScore`)
    }
  })
}
function addEvaluateItems() {
  //添加评分项目
  if (currentRow.value) {
    selectEvaluateItemsInfo.visible = true
    selectEvaluateItemsInfo.query.idNotIn = rightTableInfo.data
      .map(function (item) {
        return item.itemId || item.id
      })
      .toString()
  } else {
    proxy.$message.warning('请点击选择需要添加评分项目的评价分类！')
  }
}
function selectEvaluateItemsCallBack(data) {
  if (data && data.length) {
    let tableInfo = rightTableInfo
    data.forEach((item) => {
      item.itemId = item.id
    })
    tableInfo.data = tableInfo.data.concat(data)
    leftTableInfo.data.forEach((item) => {
      if (item.uuid === currentRow.value.uuid) {
        item['itemDetails'] = tableInfo.data
      }
    })
  }
}
function removeEvaluateItems(row) {
  //删除评分项目
  let tableInfo = rightTableInfo
  if (row && row.itemName) {
    tableInfo.data = tableInfo.data.filter((item) => item !== row)
  } else {
    tableInfo.data = tableInfo.data.filter((item) => {
      return !tableInfo.selections.includes(item)
    })
  }
  leftTableInfo.data.forEach((item) => {
    if (item.uuid === currentRow.value.uuid) {
      item['itemDetails'] = tableInfo.data
    }
  })
}
// 搜索
function getMain() {
  getEvaluateTemplateById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      leftTableInfo.data = resp.data.classifyDetails.map((item) => {
        item.uuid = proxy.$fn.getUid()
        return item
      })
    }
  })
}
function removeEvaluateClass(row) {
  let tableInfo = leftTableInfo
  if (row) {
    tableInfo.data = tableInfo.data.filter((item) => item !== row)
  } else {
    tableInfo.data = tableInfo.data.filter((item) => {
      return !tableInfo.selections.includes(item)
    })
  }
  rightTableInfo.data = []
  if (tableInfo.data.length) {
    proxy.$refs.leftTableRef.clickRow(tableInfo.data[0])
  }
}

// 触发事件
function handleEvent(event, data) {
  if (!data) {
    return
  }
  switch (event) {
    case 'tableCheck':
      leftTableInfo.selections = [...data]
      break
    case 'tableClickRow':
      currentRow.value = data
      rightTableInfo.data = data.itemDetails || []
  }
}
function handleEventRight(event, data) {
  let tableInfo = rightTableInfo
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function save() {
  let tableInfo = leftTableInfo
  if (!tableInfo.data.length) {
    proxy.$message.warning('请添加评价分类')
    return
  } else {
    let msg = ''
    let _msg = ''
    tableInfo.data.forEach((item) => {
      if (!item.itemDetails || !item.itemDetails.length) {
        msg = msg + `【${item.classifyName}】未选择评分项目，<br> `
      } else {
        item.itemDetails.forEach((el) => {
          if (!el.itemScore) {
            _msg =
              _msg +
              `【${item.classifyName}】分类下 【${el.itemName}】项目分值应该大于0，<br>`
          }
        })
      }
    })
    if (msg) {
      proxy.$alert(msg, '提示', {
        dangerouslyUseHTMLString: true,
      })
      return
    }
    if (_msg) {
      proxy.$alert(_msg, '提示', {
        dangerouslyUseHTMLString: true,
      })
      return
    }
  }
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let data = formInfo.data
    data.classifyDetails = tableInfo.data
    let api = props.id ? updateEvaluateTemplate : createEvaluateTemplate
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
function addEvaluateClass() {
  leftTableInfo.data.unshift({
    classifyName: '',
    uuid: proxy.$fn.getUid(),
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow-y: hidden;
}
</style>
